import 'dart:async';
import 'dart:convert';

import 'package:ecy_app_flutter/ecycommon/EcyCommonWidgets.dart';
import 'package:ecy_app_flutter/ecycommon/utils/EcyEncrptyUtil.dart';
import 'package:ecy_app_flutter/ecycommon/utils/EcyRegUtil.dart';
import 'package:ecy_app_flutter/routes/login/EcyPasswordLoginPage.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:keyboard_dismisser/keyboard_dismisser.dart';
import '../../EcyRouter.dart';
import '../../constant/EcyEventConsnt.dart';
import '../../constant/color_constant.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import '../../constant/constant.dart';
import '../../ecycommon/EcyEventBus.dart';
import '../../ecycommon/EcyRequestBaseManager.dart';
import '../../ecycommon/utils/EcyUserUtil.dart';
import '../../model/EcyApiCommonResponse.dart';
import 'common/CustomTextFieldWidget.dart';
import 'common/PasswordFormatter.dart';

class EcyResetPasswordPage extends EcyCommonBaseWidget {
  EcyResetPasswordPage();

  @override
  _EcyResetPasswordPageState createState() {
    return _EcyResetPasswordPageState(this);
  }
}

class _EcyResetPasswordPageState extends EcyCommonBaseWidgetState with SingleTickerProviderStateMixin {
  String mobile = "";
  String code = "";
  String pwd = "";
  String rePwd = "";
  bool pwdShowFlag = true;
  int left = 60;
  bool checked = false;
  bool canNext = false;
  bool loadingFlag = false;
  late AnimationController _controller;
  late EcyCommonBaseWidget controller;

  _EcyResetPasswordPageState(EcyCommonBaseWidget vc) {
    controller = vc;
  }

  @override
  void initState() {
    _controller = AnimationController(
      duration: const Duration(seconds: 2),
      vsync: this,
    )..repeat();
  }
  //private
  void onUpdateMobile(String newValue) {
    setState(() {
      mobile = newValue;
      checkCondtions();
    });
  }

  void onUpdatePwd(String newValue) {
    setState(() {
      pwd = newValue;
      checkCondtions();
    });
  }

  void onUpdateRePwd(String newValue) {
    setState(() {
      rePwd = newValue;
      checkCondtions();
    });
  }

  void onUpdateCode(String newValue) {
    setState(() {
      code = newValue;
      checkCondtions();
    });
  }

  void checkCondtions() {
    if (mobile.length == 11 && code.length == 6 && pwd.isNotEmpty) {
      canNext = true;
    } else {
      canNext = false;
    }
  }

  void sendSMS() async {
    if (!EcyRegUtil.validTel(mobile)) {
      EasyLoading.showToast("请输入11位合法手机号",
          duration: const Duration(seconds: 2));
      return;
    }

    countDown();

    Map<String, dynamic> body = {};
    body["tel"] = mobile;
    body["type"] = "2";
    var response =
        await EcyRequestbasemanager().get("/app/api/app/user/sms", body);
    controller.dismissLoading();
    if (response != null) {
      setState(() {
        //模型自动解析
        var resp = EcyApiCommonResponse.fromJson(response, (response) => json);
        if (resp != null) {
          String msg =
              (resp.code == 0 || resp.code == 200) ? "发送成功" : (resp.msg ?? "");
          EasyLoading.showToast(msg, duration: const Duration(seconds: 2));
        }
      });
    }
  }

  void resetPwd() async {
    if (loadingFlag) {
      return;
    }

    _loading();

    Map<String, dynamic> body = {};
    body["tel"] = mobile;
    body["captcha"] = code;
    body["password"] = EcyEncrptyUtil.aesEncode(pwd);

    try {
      var response = await EcyRequestbasemanager()
          .post("/app/api/app/user/password/captcha", body);
      if (response != null) {
        setState(() {
          //模型自动解析
          var resp =
              EcyApiCommonResponse.fromJson(response, (response) => json);
          if (resp != null) {
            if (resp.code == 0 || resp.code == 200) {
              EasyLoading.showToast(resp.msg ?? "密码修改成功， 请重新登录",
                  duration: const Duration(seconds: 2));
              EcyUserUtil.clearUserInfo();
              EcyEventBus().emit(EcyEventConst.kLogout);
              EcyRequestbasemanager().delete("/auth/logout", {});
              Navigator.of(context).pushAndRemoveUntil(
                MaterialPageRoute(
                    builder: (context) => EcyPasswordLoginPage("/", "")),
                    (Route<dynamic> route) => false,
              );
            } else {
              EasyLoading.showToast(resp.msg ?? Constant.NET_ERROR,
                  duration: const Duration(seconds: 2));
            }
          } else {
            EasyLoading.showToast(Constant.NET_ERROR);
          }
        });
      } else {
        EasyLoading.showToast(Constant.NET_ERROR);
      }
    } catch (e) {
      EasyLoading.showToast(Constant.NET_ERROR);
    } finally {
      setState(() {
        loadingFlag = false;
      });
    }
  }

  _loading() {
    setState(() {
      loadingFlag = true;
    });
  }

  countDown() {
    Timer.periodic(const Duration(seconds: 1), (Timer t) {
      if (left == 0) {
        t.cancel();
        setState(() {
          left = 60;
        });
      } else {
        if (left == 0) {
          t.cancel();
          setState(() {
            left = 60;
          });
          return;
        }
        var _left = left - 1;
        setState(() {
          left = _left;
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
        behavior: HitTestBehavior.translucent,
        child: KeyboardDismisser(
            gestures: const [
              GestureType.onTap,
              GestureType.onPanUpdateDownDirection
            ],
            child: Scaffold(
                resizeToAvoidBottomInset: false,
                backgroundColor: ColorConstant.White,
                appBar: AppBar(
                  toolbarHeight: 40.h,
                  backgroundColor: ColorConstant.White,
                  title: Text(title),
                ),
                body: Column(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Container(
                      height: 50.h,
                    ),
                    Image(
                        image: const AssetImage(
                            'assets/images/login_app_icon.png'),
                        width: 80.w,
                        height: 80.w),
                    SizedBox(
                        width: MediaQuery.of(context).size.width, height: 45.h),
                    Wrap(
                      alignment: WrapAlignment.center,
                      direction: Axis.horizontal,
                      crossAxisAlignment: WrapCrossAlignment.center,
                      spacing: 0,
                      children: [
                        Image(
                            image: const AssetImage(
                                'assets/images/ic_login_account.png'),
                            width: 24.w,
                            height: 24.w),
                        SizedBox(
                          width: MediaQuery.of(context).size.width - 60.w,
                          height: 36.h,
                          child: CustomTextFieldWidget(
                            hint: "请输入手机号",
                            inputValue: mobile,
                            updateMessageCallback2: this.onUpdateMobile,
                            textInputFormatterList: [
                              FilteringTextInputFormatter.digitsOnly,
                              LengthLimitingTextInputFormatter(11)
                            ],
                            keyboardType: TextInputType.phone,
                            obscureText: false,
                          ),
                        )
                      ],
                    ),
                    Container(
                      margin: EdgeInsets.only(
                          left: 0, right: 0, top: 10.h, bottom: 0),
                      height: 0.5.h,
                      width: MediaQuery.of(context).size.width - 40.w,
                      decoration: BoxDecoration(
                        color: Colors.grey.shade500,
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.only(
                          left: 18.w, right: 0, top: 15.h, bottom: 0),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.start,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          Image(
                              image: const AssetImage(
                                  'assets/images/ic_login_pwd.png'),
                              width: 24.w,
                              height: 24.w),
                          SizedBox(
                            width: MediaQuery.of(context).size.width - 170.w,
                            height: 36.h,
                            child: CustomTextFieldWidget(
                              hint: "请输入验证码",
                              inputValue: code,
                              updateMessageCallback2: onUpdateCode,
                              textInputFormatterList: [
                                FilteringTextInputFormatter.digitsOnly,
                                LengthLimitingTextInputFormatter(6)
                              ],
                              keyboardType: TextInputType.number,
                              obscureText: false,
                            ),
                          ),
                          GestureDetector(
                              onTap: () {
                                if (left != 60) {
                                } else {
                                  sendSMS();
                                }
                              },
                              child: Container(
                                width: 116.w,
                                height: 42.h,
                                decoration: BoxDecoration(
                                    borderRadius: BorderRadius.circular(26),
                                    border: Border.all(
                                        color: left == 60
                                            ? const Color(0xFFEA4B9B)
                                            : const Color(0xFFBFBFBF),
                                        width: 1.w)),
                                child: Center(
                                  child: Text(
                                      (left == 60 ? "发送验证码" : ("${left}s后重发")),
                                      textAlign: TextAlign.center,
                                      style: TextStyle(
                                          fontFamily: "PingFang SC",
                                          fontWeight: FontWeight.w500,
                                          fontSize: 16,
                                          color: (left == 60
                                              ? const Color(0xFFEA4B9B)
                                              : const Color(0xFFBFBFBF)))),
                                ),
                              ))
                        ],
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.only(
                          left: 0, right: 0, top: 10.h, bottom: 0),
                      height: 0.5.h,
                      width: MediaQuery.of(context).size.width - 40.w,
                      decoration: BoxDecoration(
                        color: Colors.grey.shade500,
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.only(
                          left: 0, right: 0, top: 20.h, bottom: 0),
                      child: Wrap(
                        alignment: WrapAlignment.center,
                        direction: Axis.horizontal,
                        crossAxisAlignment: WrapCrossAlignment.center,
                        spacing: 0,
                        children: [
                          Image(
                              image: const AssetImage(
                                  'assets/images/ic_login_pwd.png'),
                              width: 24.w,
                              height: 24.w),
                          SizedBox(
                            width: MediaQuery.of(context).size.width - 80.w,
                            height: 36.h,
                            child: CustomTextFieldWidget(
                              hint: "请输入6位及以上密码",
                              inputValue: pwd,
                              updateMessageCallback2: onUpdatePwd,
                              textInputFormatterList: [
                                PasswordFormatter(),
                                LengthLimitingTextInputFormatter(50)
                              ],
                              keyboardType: TextInputType.text,
                              obscureText: pwdShowFlag,
                            ),
                          ),
                          GestureDetector(
                            onTap: () {
                              setState(() {
                                pwdShowFlag = !pwdShowFlag;
                              });
                            },
                            child: Icon(
                              pwdShowFlag
                                  ? CupertinoIcons.eye
                                  : CupertinoIcons.eye_slash,
                              size: 18,
                            ),
                          )
                        ],
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.only(
                          left: 0, right: 0, top: 10.h, bottom: 0),
                      height: 0.5.h,
                      width: MediaQuery.of(context).size.width - 40.w,
                      decoration: BoxDecoration(
                        color: Colors.grey.shade500,
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.only(
                          left: 0, right: 0, top: 20.h, bottom: 0),
                      child: Wrap(
                        alignment: WrapAlignment.center,
                        direction: Axis.horizontal,
                        crossAxisAlignment: WrapCrossAlignment.center,
                        spacing: 0,
                        children: [
                          Image(
                              image: const AssetImage(
                                  'assets/images/ic_login_pwd.png'),
                              width: 24.w,
                              height: 24.w),
                          SizedBox(
                            width: MediaQuery.of(context).size.width - 80.w,
                            height: 36.h,
                            child: CustomTextFieldWidget(
                              hint: "请再次输入密码",
                              inputValue: rePwd,
                              updateMessageCallback2: onUpdateRePwd,
                              textInputFormatterList: [
                                PasswordFormatter(),
                                LengthLimitingTextInputFormatter(50)
                              ],
                              keyboardType: TextInputType.text,
                              obscureText: pwdShowFlag,
                            ),
                          ),
                          GestureDetector(
                            onTap: () {
                              setState(() {
                                pwdShowFlag = !pwdShowFlag;
                              });
                            },
                            child: Icon(
                              pwdShowFlag
                                  ? CupertinoIcons.eye
                                  : CupertinoIcons.eye_slash,
                              size: 18,
                            ),
                          )
                        ],
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.only(
                          left: 0, right: 0, top: 15.h, bottom: 0),
                      height: 0.5.h,
                      width: MediaQuery.of(context).size.width - 40.w,
                      decoration: BoxDecoration(
                        color: Colors.grey.shade500,
                      ),
                    ),
                    GestureDetector(
                        onTap: () {
                          FocusScope.of(context).requestFocus(FocusNode());
                          if (!EcyRegUtil.validTel(mobile)) {
                            EasyLoading.showToast("请输入11位合法手机号",
                                duration: const Duration(seconds: 2));
                            return;
                          }
                          if (code.isEmpty) {
                            EasyLoading.showToast("请输入验证码",
                                toastPosition: EasyLoadingToastPosition.bottom,
                                duration: const Duration(seconds: 1));
                            return;
                          }
                          if (pwd.length < 6) {
                            EasyLoading.showToast("密码长度最小6位",
                                duration: const Duration(seconds: 1));
                            return;
                          }
                          if (rePwd.isEmpty) {
                            EasyLoading.showToast("请再次输入密码",
                                toastPosition: EasyLoadingToastPosition.bottom,
                                duration: const Duration(seconds: 1));
                            return;
                          }
                          if (pwd != rePwd) {
                            EasyLoading.showToast("两次输入密码不一致，请重新输入",
                                toastPosition: EasyLoadingToastPosition.bottom,
                                duration: const Duration(seconds: 1));
                            return;
                          }
                          if (!checked) {
                            EasyLoading.showToast("请先勾选协议",
                                toastPosition: EasyLoadingToastPosition.bottom,
                                duration: const Duration(seconds: 1));
                            return;
                          }
                          resetPwd();
                        },
                        child: Container(
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(26.r),
                            color: ColorConstant.CommonColor,
                          ),
                          margin: EdgeInsets.only(
                              left: 22, right: 22, top: 35.h, bottom: 10.0),
                          width: MediaQuery.of(context).size.width - 44.w,
                          height: 52.h,
                          alignment: Alignment.center,
                          child: Stack(
                            children: [
                              SizedBox(
                                height: 45.h,
                                width: 45.w,
                                child: Align(
                                  alignment: Alignment.center,
                                  child: Transform.translate(
                                    offset: const Offset(-35.0, 0.0),
                                    child: loadingFlag
                                        ? Image.asset(
                                        width: 28.w,
                                        height: 25.h,
                                        alignment: Alignment.center,
                                        "assets/images/loading/loading.gif")
                                        : null,
                                  ),
                                ),
                              ),
                              SizedBox(
                                  height: 45.h,
                                  width: 50.h,
                                  child: Align(
                                    alignment: Alignment.center,
                                    child: Text('保存',
                                        textAlign: TextAlign.center,
                                        style: TextStyle(
                                            fontFamily: "PingFang SC",
                                            fontWeight: FontWeight.w500,
                                            fontSize: 18.sp,
                                            color: ColorConstant.White)),
                                  )),
                            ],
                          ),
                        )),
                    Expanded(
                      child: Container(
                        color: Colors.transparent,
                      ),
                    ),
                    Padding(
                      padding: const EdgeInsets.only(left: 10),
                      child: Wrap(
                        direction: Axis.horizontal,
                        spacing: 0,
                        children: [
                          GestureDetector(
                            behavior: HitTestBehavior.opaque,
                            onTap: () => {
                              setState(() {
                                checked = !checked;
                              }),
                            },
                            child: Image(
                                image: AssetImage(checked
                                    ? 'assets/images/login_checked.png'
                                    : 'assets/images/login_unchecked.png'),
                                width: 22.w,
                                height: 22.w),
                          ),
                          SizedBox(
                            width: MediaQuery.of(context).size.width - 40.w,
                            child: GestureDetector(
                              onTap: () {},
                              child: Padding(
                                  padding: const EdgeInsets.only(top: 3),
                                  child: RichText(
                                    text: TextSpan(
                                      children: [
                                        TextSpan(
                                          text: ' 已详细阅读并同意',
                                          style: TextStyle(
                                              color: const Color.fromARGB(
                                                  255, 140, 140, 140),
                                              fontSize: 12.sp),
                                        ),
                                        TextSpan(
                                            recognizer: TapGestureRecognizer()
                                              ..onTap = () {
                                                EcyRouter.pushNoParams(
                                                    context,
                                                    EcyRouter
                                                        .privacyPolicyPage);
                                              },
                                            text: '《使用条款和个人信息保护政策》',
                                            style: TextStyle(
                                                color:
                                                    ColorConstant.CommonColor,
                                                fontSize: 12.sp)),
                                      ],
                                    ),
                                  )),
                            ),
                          ),
                        ],
                      ),
                    ),
                    SizedBox(
                        width: MediaQuery.of(context).size.width, height: 40.h),
                  ],
                ))),
        onTap: () {
          //触摸收起键盘
          FocusScope.of(context).requestFocus(FocusNode());
        });
  }
}
